//
//  CoreDataEntity.m
//  UESTCPioneer
//
//  Created by Apple on 14-11-15.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "CoreDataEntity.h"
#import "EMBuddy.h"

@implementation CoreDataEntity
single_implementation(CoreDataEntity)

+(void)branchEntityFromDictionary:(NSDictionary *)dict context:(NSManagedObjectContext *)context{
    BranchEntity * entity = [NSEntityDescription insertNewObjectForEntityForName:@"BranchEntity" inManagedObjectContext:context];
    entity.instituteNo = [dict objectForKey:@"instiNO"];
    entity.instituteName = [dict objectForKey:@"institute"];
//    return entity;
}


+(void)userFromDictionary:(NSDictionary*)aDic context:(NSManagedObjectContext *)context
{
    UserInfoEntity *user=[NSEntityDescription insertNewObjectForEntityForName:@"UserInfoEntity" inManagedObjectContext:context];
    
    user.instituteNo = [aDic objectForKey:@"instiNo"];
    user.branchInfo = [aDic objectForKey:@"branchInfo"];
    user.partyNo = [aDic objectForKey:@"partyNo"];
    user.headUrl= [aDic objectForKey:@"headUrl"];
    user.name= [aDic objectForKey:@"name"];
    user.userID= [aDic objectForKey:@"userID"];
    user.userName= [aDic objectForKey:@"userName"];
    
//    return user;
}

+(void)subPartyEntityFromDictionary:(NSDictionary*)aDic context:(NSManagedObjectContext *)context
{
    SubPartyEntity *subParty=[NSEntityDescription insertNewObjectForEntityForName:@"SubPartyEntity" inManagedObjectContext:context];
    subParty.instituteNo = [aDic objectForKey:@"instiNO"];
    subParty.partyName = [aDic objectForKey:@"partyName"];
    subParty.partyNo = [aDic objectForKey:@"partyNo"];
//    return subParty;
}

#pragma mark  -数据库操作方法
/**
 *打开数据库
 */
+(NSManagedObjectContext *)openDB{
    
    //1.实例化数据模型()
    NSManagedObjectModel * model = [NSManagedObjectModel mergedModelFromBundles:nil];
    
    //2.实例化持久化存储调度，要建立起桥梁，需要模型
    NSPersistentStoreCoordinator * store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    //3.添加一个持久化的数据库到存储调度。
    //3.1建立数据库保存到沙盒的URL
    NSArray * docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* myUserId = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_LoginName];
    NSString * path = [docs[0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@addressbook.db",myUserId]];
    NSURL * url = [NSURL fileURLWithPath:path];
    
    //3.2打开或者新建数据库文件
    //如果文件不存在，则新建之后打开
    //否则直接打开数据库
    NSError * error = nil;
    [store addPersistentStoreWithType:NSSQLiteStoreType
                        configuration:nil URL:url
                              options:nil
                                error:&error];
    
    if (error) {
        NSLog(@"打开数据库失败 -- %@ !",error.localizedDescription);
        return nil;
    } else {
        NSLog(@"打开数据库成功!");
        NSManagedObjectContext * context = [[NSManagedObjectContext alloc] init];
        context.persistentStoreCoordinator = store;
//        _context = context;
         return context;
    }
}

//#pragma mark 新增数据
//-(void)addData{
//    
//    //
//    BranchEntity * branch = [NSEntityDescription insertNewObjectForEntityForName:@"BranchEntity" inManagedObjectContext:_context];
//    
//    //
//    branch.instituteNo = @"001";
//    branch.instituteName = @"通信与信息工程学院";
//    
//    //
//    NSError * error = nil;
//    if ([_context save:&error]) {
//        NSLog(@"新增记录成功!");
//    } else {
//        NSLog(@"新增记录失败!");
//    }
//    
//}


//#pragma mark 查询
//-(void)selectAllBranch:(NSString * )branch{
//    
//    //查询所有信息
//    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"BranchEntity"];
//    
//    //条件查询
//    request.predicate = [NSPredicate predicateWithFormat:@"institute = 001 && instituteName LIKE '*信'"];
//    
//    //在谓词中CONTAINS类似于数据库中的LIKE '%通%'
//    //如果通过key path 查询字段，需要使用%K
//    request.predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS '通'",branch];
//    
//    //
//    NSArray * array = [_context executeFetchRequest:request error:nil];
//    NSLog(@"array = %@",array);
//    
//    for(BranchEntity * b in array){
//        NSLog(@"%@",b.instituteName);
//    }
//}

+(void)saveNewBranch:(BranchEntity *)entity context:(NSManagedObjectContext *)context{

    NSError * error = nil;
    if ([context save:&error]) {
//        NSLog(@"新增记录成功:%@!",entity.instituteName);
    } else {
        NSLog(@"新增记录失败:%@!",entity.instituteName);
    }
}

+(void)saveNewSubParty:(SubPartyEntity *)entity context:(NSManagedObjectContext *)context{
    
    NSError * error = nil;
    if ([context save:&error]) {
//        NSLog(@"新增记录成功%@!",entity.partyName);
    } else {
        NSLog(@"新增记录失败%@!",entity.partyName);
    }
    
}

+(void)saveNewUserInfo:(UserInfoEntity *)userInfo context:(NSManagedObjectContext *)context{
    
    NSError * error = nil;
    if ([context save:&error]) {
//        NSLog(@"新增记录成功%@!",userInfo.userName);
    } else {
        NSLog(@"新增记录失败%@!",userInfo.userName);
    }
}

#pragma mark 根据用户ID获取用户信息
+(UserInfoEntity*)getUserByUserId:(NSString*)userId
{
    //查询所有信息
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"UserInfoEntity"];
    
    //条件查询
    request.predicate = [NSPredicate predicateWithFormat:@"userID = %@",userId];
    
    //
    NSArray * array = [[CoreDataEntity sharedCoreDataEntity].context executeFetchRequest:request error:nil];
    
    for(UserInfoEntity * b in array){
        return b;
    }
    return nil;
}

#pragma mark 查询所有用户
+(NSMutableArray *)selectAllUserInfo{

    //查询所有信息
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"UserInfoEntity"];
    
    NSMutableArray * marray = [NSMutableArray array];
    NSArray * array = [[CoreDataEntity sharedCoreDataEntity].context executeFetchRequest:request error:nil];
    NSLog(@"array.count = %i",array.count);
    for (UserInfoEntity * user  in array) {
        EMBuddy * buddy = [[EMBuddy alloc] init];
//        buddy.username = user.name;
        buddy.username = user.userID;
        buddy.isPendingApproval = NO;
        buddy.followState = 3;
        [marray addObject:buddy];
    }
    return marray;
}

#pragma mark 查询所有党支部
+(NSArray *)selectAllSubParty{
    //查询所有信息
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SubPartyEntity"];
    NSArray * array = [[CoreDataEntity sharedCoreDataEntity].context executeFetchRequest:request error:nil];
    return array;
}

+(NSMutableArray *)selectAllUserInfoWithPartyId:(NSString *)partyId{
    
    //查询所有信息
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"UserInfoEntity"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"partyNo = '%@'",partyId]];
    NSMutableArray * marray = [NSMutableArray array];
    NSArray * array = [[CoreDataEntity sharedCoreDataEntity].context executeFetchRequest:request error:nil];
    for (UserInfoEntity * user  in array) {
        EMBuddy * buddy = [[EMBuddy alloc] init];
        //        buddy.username = user.name;
        buddy.username = user.userID;
        buddy.isPendingApproval = NO;
        buddy.followState = 3;
        [marray addObject:buddy];
    }
    return marray;
}


//- (void) fetchObjects
//{
//    // 创建Request
//    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context]];
//    
//    // 添加一个排序描述
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:nil];
//    NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
//    [fetchRequest setSortDescriptors:descriptors];
//    [sortDescriptor release];
//    
//    // 初始化results controller，cache叫Root
//    NSError *error;
//    self.results = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.context sectionNameKeyPath:nil cacheName:@"Root"];
//    self.results.delegate = self;
//    // 查询
//    if (![[self results] performFetch:&error])  NSLog(@"Error: %@", [error localizedDescription]);
//    
//}

+(BOOL)haveCreateBranchAndSubPartyWithContext:(NSManagedObjectContext *)context
{
   //查询Branch所有信息
   NSFetchRequest * branchRequest = [NSFetchRequest fetchRequestWithEntityName:@"BranchEntity"];
   NSArray * branchArray = [context executeFetchRequest:branchRequest error:nil];

   //查询所有SubParty信息
   NSFetchRequest * subPartyRequest = [NSFetchRequest fetchRequestWithEntityName:@"SubPartyEntity"];
   NSArray * subPartyArray = [context executeFetchRequest:subPartyRequest error:nil];
    
   if ([subPartyArray count] > 0 && [branchArray count] > 0) {
        return YES;
   }
    
   return NO;
}


+(BOOL)haveSaveUserByUserId:(NSString *)userId context:(NSManagedObjectContext *)context{

    NSFetchRequest * userInfoRequest = [NSFetchRequest fetchRequestWithEntityName:@"UserInfoEntity"];
    userInfoRequest.predicate = [NSPredicate predicateWithFormat:@"userID = %@",userId];
    NSArray * userInfoArray = [context executeFetchRequest:userInfoRequest error:nil];
    if (userInfoArray.count > 0) {
        return YES;
    }
    return NO;
}

+(NSArray*)fetchAllBranchsWithContext:(NSManagedObjectContext *)context
{
    //查询Branch所有信息
    NSFetchRequest * branchRequest = [NSFetchRequest fetchRequestWithEntityName:@"BranchEntity"];
    NSArray * branchArray = [context executeFetchRequest:branchRequest error:nil];
    return branchArray;
}

+(NSArray *)getSubPartyByInstiNo:(NSString*)instiNo  context:(NSManagedObjectContext *)context
{
    NSFetchRequest * subPartyRequest = [NSFetchRequest fetchRequestWithEntityName:@"SubPartyEntity"];
    subPartyRequest.predicate = [NSPredicate predicateWithFormat:@"instituteNo = %@",instiNo];
    NSArray * subPartyArray = [context executeFetchRequest:subPartyRequest error:nil];
    return subPartyArray;
}

+(NSArray*)getUsersByPartyNo:(NSString*)partyNo  context:(NSManagedObjectContext *)context
{
    NSFetchRequest * userInfoRequest = [NSFetchRequest fetchRequestWithEntityName:@"UserInfoEntity"];
    userInfoRequest.predicate = [NSPredicate predicateWithFormat:@"partyNo = %@",partyNo];
    NSArray * userInfoArray = [context executeFetchRequest:userInfoRequest error:nil];
    return userInfoArray;
}
+(NSString *)selectUserNameWithUserId:(NSString *)userId{

    NSFetchRequest * userInfoRequest = [NSFetchRequest fetchRequestWithEntityName:@"UserInfoEntity"];
    userInfoRequest.predicate = [NSPredicate predicateWithFormat:@"userID = %@",userId];
    NSArray * userInfoArray = [[CoreDataEntity sharedCoreDataEntity].context executeFetchRequest:userInfoRequest error:nil];
    if (userInfoArray.count > 0) {
        UserInfoEntity * user = userInfoArray[0];
        return user.name;
    } else {
        return nil;
    }
}

@end
